import 'dart:async';
import 'package:get/get.dart';
import 'package:flutter/cupertino.dart';
import 'package:flutter/material.dart';
import 'package:flutter1/card_game/constant.dart';
import 'package:flutter1/card_game/card.dart';

class SecondPage extends StatefulWidget {
  @override
  _SecondPageState createState() => _SecondPageState();
}

class _SecondPageState extends State<SecondPage> {
  late Timer _timer;

  void dispose() {
    _timer.cancel();
    super.dispose();
  }

  int _start = 10;

  void startTimer() {
    const oneSec = const Duration(seconds: 1);

    _timer = Timer.periodic(oneSec, (timer) {
      _start += 1;
      setState(() {});
    });
  }

  ///////////////////////
  int finalGrade = 0;

  void initState() {
    super.initState();

    startTimer();
  }

  //获取的是枚举类型列表
  List<String> numList = List.generate(16, (index) => candidates[index ~/ 2])
    ..shuffle();

  List<bool> newIsFrontList = List.generate(16, (index) => false);

  //维护一个记录卡片状态的bool列表。
  List<String> correctNumList = [];

  Map<String, dynamic> flipCardInfo = {};

  void onCardTap(int idx, String str) async {
    if (newIsFrontList[idx] == false) {
      if (flipCardInfo.isEmpty) {
        flipCardInfo = {"idx": idx, "str": str};
      } else {
        if (flipCardInfo["str"] == str) {
          print('成功消除！');
          finalGrade += 25;
          correctNumList.add(str);
          flipCardInfo = {};
        } else {
          flipCardInfo = {"idx": idx, "str": str};
        }
      }

      //idx是卡片的索引，num是卡片的内容
      setState(() {
        newIsFrontList[idx] = !newIsFrontList[idx];
      });
      print('你按到的是索引$idx的内容$num的卡片！\n $str');
      print(flipCardInfo);

      if (newIsFrontList[idx] == true) {
        Future.delayed(Duration(seconds: 1, milliseconds: 500), () {
          newIsFrontList[idx] = !newIsFrontList[idx];
          setState(() {
            print(flipCardInfo);
          });
        });
      }

      finalGrade -= 2;
      //    点一次肯定要减分的！
    } else {
      print('正在翻面中！请不要触碰！');
    }
  }

  ////////////////////

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        title: Text('消消看'),
      ),
      body: Container(
        alignment: Alignment.center,
        child: Column(
          mainAxisSize: MainAxisSize.min,
          children: [
            Container(
              padding: EdgeInsets.only(bottom: 42),
              // width: cardSize * 4,
              // height: cardSize * 4,
              child: correctNumList.length == 8
                  ? Center(
                      child: Text(
                      '恭喜你挑战成功！\n得分$finalGrade',
                      style: TextStyle(fontSize: 24),
                    ))
                  : Column(
                      children: [
                        Padding(
                          padding: EdgeInsets.all(40),
                          child: DecoratedBox(
                            decoration: BoxDecoration(
                              boxShadow: <BoxShadow>[
                                BoxShadow(
                                    color: CupertinoColors.activeBlue,
                                    offset: Offset(1, 2),
                                    spreadRadius: 2)
                              ],
                              borderRadius: BorderRadius.circular(20),
                            ),
                            child: ListTile(
                              minLeadingWidth: 20,
                              title: Text(
                                "当前得分:            $finalGrade            ",
                                style: TextStyle(color: Colors.white),
                              ),
                            ),
                          ),
                        ),
                        Wrap(
                          children: numList
                              .asMap()
                              //idx是卡片的索引，num是卡片的内容
                              .map((idx, num) => MapEntry(
                                  idx,
                                  correctNumList.contains(num)
                                      ? Container(
                                          width: cardSize,
                                          height: cardSize,
                                        )
                                      : //如果correctNumList里面有这个数那么就不会显示
                                      FlipCard(
                                          str: num,
                                          isFront: newIsFrontList[idx],
                                          onTap: () => onCardTap(idx, num),
                                          isSelecting:
                                              flipCardInfo["idx"] == idx,
                                        )))
                              .values
                              .toList(),
                        ),
                      ],
                    ),
            ),
            Wrap(
              children: [
                ElevatedButton(
                    onPressed: () {
                      setState(() {
                        flipCardInfo = {};
                        correctNumList = [];
                        newIsFrontList = List.generate(16, (index) => false);
                        numList =
                            List.generate(16, (index) => candidates[index ~/ 2])
                              ..shuffle();
                      });
                    },
                    child: Text('初始化')),
                Padding(padding: EdgeInsets.all(2)),
                ElevatedButton(
                    onPressed: () {
                      Get.defaultDialog(
                          radius: 2,
                          contentPadding: EdgeInsets.only(top: 60, bottom: 50),
                          content: Row(
                            mainAxisSize: MainAxisSize.min,
                            children: [
                              CircularProgressIndicator(),
                              Padding(
                                padding: EdgeInsets.all(8.0),
                              ),
                              ElevatedButton(
                                  onPressed: () => print('不错'),
                                  child: Text('我是一个内部的按钮'))
                            ],
                          ),
                          title: '是否上车？');
                    },
                    child: Text('是否上车？')),
                Padding(padding: EdgeInsets.all(2)),
                ElevatedButton(
                    onPressed: () => Get.snackbar('这是一个snackBar', "欢迎使用",
                        barBlur: 22, borderRadius: 23, colorText: Colors.white),
                    child: Text("显示snackBar"))
              ],
            )
          ],
        ),
      ),
    );
  }
}
